﻿// Inner Fire 游戏引擎库
// 渲染项目类
//
// Copyright (c) 2024 by 尔西大帝. All rights reserved.
//
// 就是相当于GameObject。用于每个项目
//
// Author: 尔西大帝
// Email: 2670613871@qq.com
// Created: 2024-12-03

#include "render_item.h"
#include <xml_reader.h>
using namespace ikit;

namespace ifire::dx {
void RenderItem::Update(UploadBuffer<ObjectConstants>* buffer) {
  // 仅当项目已经发生变化时才设置
  if (frame_dirty_count == 0) {
    return;
  }

  // 设置世界矩阵
  XMMATRIX world_mat = XMLoadFloat4x4(&world);
  XMMATRIX tex_mat = XMLoadFloat4x4(&texture_transform);

  ObjectConstants obj_constants;

  XMStoreFloat4x4(&obj_constants.world, XMMatrixTranspose(world_mat));
  XMStoreFloat4x4(&obj_constants.tex_transform, XMMatrixTranspose(tex_mat));
  obj_constants.DisplacementMapTexelSize = DisplacementMapTexelSize;
  obj_constants.GridSpatialStep = GridSpatialStep;

  // 设置材质
  if (material == nullptr) {
    obj_constants.material_index = 0;
  } else {
    obj_constants.material_index = material->Index();
  }

  // 需要复制到object_buffer_index指针的位置
  buffer->CopyData(cb_index, obj_constants);

  // 其它的帧同样也要更新
  frame_dirty_count--;
}

void RenderItem::SetTiling(const XMFLOAT2& tiling) {
  tiling_ = tiling;
  auto tiling_mat = XMMatrixScaling(tiling.x, tiling.y, 1.0f);
  XMStoreFloat4x4(&texture_transform, tiling_mat);
}

void RenderItem::SetWorldMatrix(FXMMATRIX mat) {
  XMStoreFloat4x4(&world, mat);
  SetRefresh();
}


} // namespace ifire::dx
